<template>
  <van-search
    :show-action="true"
    @cancel="cancel"
    @clear="clear"
    @input="input"
    @focus="focus"
    autofocus
    background="#3196fa"
    clearable
    placeholder="请输入搜索关键词"
    round
    v-model="keyword"
  />
</template>

<script>
import { getSuggestions } from "../../../network/home";

export default {
  name: "SearchBar",
  components: {},
  props:['value'],
  watch:{
    value(val) {
      this.keyword = val
    }
  },
  data() {
    return {
      keyword: "",
      timer: null, //定时器,防抖
    };
  },
  methods: {
    input(val) {
      clearTimeout(this.timer);
      this.timer = setTimeout(async _ => {
        if (val.trim()) {
          const result = await getSuggestions(val);
          console.log(result);
          if (result.message === "OK") {
            this.$bus.$emit("sendSearchData", result.data, val);
          }
        } else {
          this.$bus.$emit("sendSearchData", { options: [] });
          this.$bus.$emit('sendSearchList')
        }
      }, 300);
    },
    clear() {
      this.$bus.$emit("sendSearchData", { options: [] });
      this.$bus.$emit('sendSearchList')
    },
    cancel() {
      if (this.keyword.trim()) {
        this.$bus.$emit("sendSearchData", { options: [] });
        this.$bus.$emit('sendSearchList')
      }
    },
    focus() {
      // this.input()
      this.$emit('goSugs')
    }
  }
};
</script>

<style scoped lang="stylus">
.van-search
  height 46px

.van-search__action
  color #fff
</style>